﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace HB.Base
{
    /// <summary>
    /// ICO容器
    /// </summary>
    public class SimpleIOC
    {
        static ConcurrentDictionary<string, object> DicObj;
        static SimpleIOC()
        {
            DicObj = new ConcurrentDictionary<string, object>();
        }
        /// <summary>
        /// 注入实例
        /// </summary>
        /// <param name="key"></param>
        /// <param name="overWrite">重复时是否覆盖</param>
        /// <param name="value"></param>
        public static void Register<T>(T value, string key = null,bool overWrite=false ) where T : class
        {
            if (key == null) { key = typeof(T).FullName; }
            if (!DicObj.ContainsKey(key))
            {
                DicObj.TryAdd(key, value);
            }else
            {
                if(overWrite)
                {
                    DicObj[key] = value;
                }else
                {
                    throw new Exception($"typeof:{typeof (T).FullName },name {key } is already exists");
                }
            }
        }

        /// <summary>
        /// 取得实例
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Resolve<T>(string key = null) where T : class
        {
            if (key == null) { key = typeof(T).FullName; }
            if (DicObj.ContainsKey(key))
            {
                return DicObj[key] as T;
            }
            return default(T);
        }
        /// <summary>
        /// 清理所有实例引用
        /// </summary>
        public static void Clear()
        {
            DicObj.Clear();
        }
    }
}
